package hanlder

import (
	"cart_srv/cart"
	"cart_srv/global"
	"cart_srv/goods"
	"cart_srv/model"
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type CartService struct {
	cart.UnimplementedCartServer
}

// 添加购物车
func (c *CartService) CreateCart(ctx context.Context, in *cart.CreateCartRequest) (*cart.CreateCartResponse, error) {
	//判断商品是否存在
	_, err := global.GoodsService.GetGoodsDetail(context.Background(), &goods.GetGoodsDetailRequest{GoodsId: in.GoodsId})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "商品不存在，添加购物车失败")
	}

	//判断购物车中是否存在该商品
	var cartInfo model.Cart

	tx := global.DB.Model(&model.Cart{}).Where(model.Cart{
		UserId:  in.UserId,
		GoodsId: in.GoodsId,
	}).Limit(1).Find(&cartInfo)

	m := model.Cart{
		UserId:  in.UserId,
		GoodsId: in.GoodsId,
		Stock:   in.Stock,
	}
	if tx.RowsAffected == 0 {
		tx := global.DB.Model(&model.Cart{}).Create(&m)
		if tx.Error != nil {
			return nil, status.Errorf(codes.Internal, "添加购物车失败")
		}
	} else {
		m.Stock += in.Stock
		tx := global.DB.Model(&model.Cart{}).Update("Stock", m.Stock)
		if tx.Error != nil {
			return nil, status.Errorf(codes.Internal, "更新购物车失败")
		}
	}

	return &cart.CreateCartResponse{CartId: int32(m.ID)}, nil
}

// 删除购物车
func (c *CartService) DeleteCart(ctx context.Context, in *cart.DeleteCartRequest) (*cart.DeleteCartResponse, error) {

	var cartInfo model.Cart

	tx := global.DB.Model(&model.Cart{}).Where("goods_id = ? and user_id = ? ", in.GoodsId, in.UserId).Delete(&cartInfo)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "删除购物车失败")
	}
	return &cart.DeleteCartResponse{}, nil
}

func (c *CartService) CartDetail(ctx context.Context, in *cart.CartDetailRequest) (*cart.CartDetailResponse, error) {
	var cartInfo model.Cart
	tx := global.DB.Model(&model.Cart{}).Where(model.Cart{
		UserId: in.UserId,
		Check:  1,
	}).First(&cartInfo)

	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询购物车失败")
	}

	return &cart.CartDetailResponse{
		Id:      int32(cartInfo.ID),
		UserId:  cartInfo.UserId,
		GoodsId: cartInfo.GoodsId,
		Stock:   cartInfo.Stock,
	}, nil
}
